import { create } from "zustand";
import { persist } from "zustand/middleware";

type Theme = "light" | "dark";

interface ThemeState {
  theme: Theme;
  toggleTheme: () => void;
  init: () => void;
}

function applyTheme(theme: Theme): void {
  document.documentElement.setAttribute("data-theme", theme);
}

const useThemeStore = create<ThemeState>()(
  persist(
    (set, get) => ({
      theme: "light",
      toggleTheme: () => {
        const currentTheme = get().theme;
        const newTheme = currentTheme === "light" ? "dark" : "light";
        set({ theme: newTheme });
        applyTheme(newTheme); // Apply theme to document
      },
      init: () => {
        const currentTheme = get().theme;
        console.log("init theme: ", currentTheme);
        applyTheme(currentTheme);
      },
    }),
    { name: "theme" },
  ),
);

export default useThemeStore;
